<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>受控组件</title>
  </head>
  <body>
    <div id="test">我是一段文本</div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
      // 创建类式组件
      class Life extends React.Component {
        state = {
          opacity: 1
        }

        delComponent = () => {
          // 卸载组件方法
          ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }

        // 组件卸载前调用
        componentWillUnmount() {
          clearInterval(this.timer)
        }

        // 组件挂载后调用
        componentDidMount() {
          this.timer = setInterval(() => {
            let { opacity } = this.state
            opacity -= 0.1
            if (opacity <= 0) {
              opacity = 1
            }
            this.setState({ opacity })
          }, 200)
        }

        // 组价初次渲染、更新时调用
        render() {
          const { opacity } = this.state
          return (
            <div>
              <h2 style={{ opacity }}>react生命周期</h2>
              <button onClick={this.delComponent}>卸载组件</button>
            </div>
          )
        }
      }

      ReactDOM.render(<Life />, document.getElementById('test'))
    </script>
  </body>
</html>
